<template>
  <a-select
    v-model="arrayValue"
    :disabled="disabled"
    :mode="multiple ? 'multiple' : 'default'"
    showSearch
    :placeholder="placeholder"
    :getPopupContainer="getParentContainer"
    :filterOption="false"
    :allowClear="allowClear"
    :showArrow="false"
    @search="loadData"
    @change="onChange"
    :notFoundContent="loading ? undefined : null">
     <a-spin v-if="loading" slot="notFoundContent" size="small"/>
    <a-select-option
      v-for="(item,index) in dictOptions"
      :key="index"
      :value="item.value">
      <span style="display: inline-block;width: 100%" :title=" item.text || item.label ">
        {{ item.text || item.label }}
      </span>
    </a-select-option>
  </a-select>

</template>

<script>
import { ajaxGetDictItems, getDictItemsFromCache} from '@/api/api'
   import { getAction } from '@/api/manage'
  import { simpleDebounce } from '@/utils/util'
  export default {
    name: 'JSearchSelectMultipleUser',
    props: {
      dict: {
        type: String,
        default: "sys_user,username,username,system",
        required: false
      },
      disabled: Boolean,
      value: String,
      type: String,
      options:Array,
      multiple:{        //是否多选
        type:Boolean,
        default:false,
      },
      placeholder:{
        type:String,
        default:"请输入并选择",
        required:false
      },
      spliter:{
        type: String,
        required: false,
        default: ','
      },
      popContainer:{
        type:String,
        default:'',
        required:false
      },
      allowClear: {     //是否允许清除选中项
        type: Boolean,
        default:true
      },
      pageSize:{
        type:Number,
        default:20
      },
    },
  data() {
      this.lastLoad = 0;
      return {
        dictOptions: [],
        arrayValue: [],
        loading:false
      }
    },

    watch:{
      options: function(val){
        this.setCurrentDictOptions(val);
      },
      "value":{
        immediate:true,
        handler(val){
          if(!val){
            this.arrayValue = []
            this.dictOptions =[]
          }else{
            this.initSelectValue()
          }
        }
      },
    },
    methods: {
      //有值，初始化的时候，如绑定字段，显示字段是username，则不需要调翻译接口，
      initSelectValue(){
        if(!this.arrayValue || this.arrayValue!=this.value){
          if(this.dict && (this.dict.split(',')[1] === this.dict.split(',')[2]) && this.dict.split(',')[2] === 'username'){
             this.arrayValue = this.value.split(this.spliter)
          }else{
            getAction('/sys/user/getAllUserByOrg', { keyword: this.value }).then(res => {    
              this.loading = false  
              if (res.success) {    
                let dictOptions = res.result ? res.result : [];
                this.dictOptions = dictOptions.map(item => {
                  return {
                    text: item.username,
                    value: item.username
                  }
                })
              } else {
                this.$message.warning(res.message)
              }
               this.arrayValue = this.value.split(this.spliter)
           })
          }
        }
      },
    //搜索模糊查询
      loadData: simpleDebounce(function(value){
        if (value) {
          this.lastLoad += 1
          const currentLoad = this.lastLoad
          this.dictOptions = []
          this.loading = true
          getAction('/sys/user/getAllUserByOrg', { keyword: value, pageSize: this.pageSize }).then(res => {
            this.loading = false
            if (res.success) {
              if (currentLoad != this.lastLoad) {
                return
              }
              let dictOptions = res.result ? res.result : [];
              this.dictOptions = dictOptions.map(item => {
                  return {
                    text: item.username,
                    value: item.username
                  }
                })
            } else {
              this.$message.warning(res.message)
            }
          })
        } else { 
          this.dictOptions = []
        }
      }, 500),
       //选中项
      onChange(selectedValue) {
        if(this.multiple){
        if (selectedValue && selectedValue.length>0) {
          this.$emit('change', selectedValue.join(this.spliter));
        } else {
          this.arrayValue = []
          this.dictOptions = []
          this.$emit('change', null);
        }
        }else{
          this.$emit('change', selectedValue);
        }
      },
      setCurrentDictOptions(dictOptions){
        this.dictOptions = dictOptions
      },
      getCurrentDictOptions(){
        return this.dictOptions
      },
      getParentContainer(node){
        if(!this.popContainer){
          return node.parentNode
        }else{
          return document.querySelector(this.popContainer)
        }
      },
      filterOption(input, option) {
        return option.componentOptions.children[0].children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      }

    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>
